<template>
  <div ref="chartContainer" class="echarts-container"></div>
</template>

<script>
export default {
  name: 'EchartsWrapper',
  props: {
    options: {
      type: Object,
      required: true
    },
    theme: {
      type: [String, Object],
      default: null
    }
  },
  data() {
    return {
      chartInstance: null
    }
  },
  mounted() {
    this.initChart()
    this.addResizeListener()
  },
  beforeDestroy() {
    this.removeResizeListener()
    this.disposeChart()
  },
  methods: {
    //初始化图标
    initChart() {
      this.chartInstance = this.$echarts.init(this.$refs.chartContainer, this.theme)
      this.updateChart()
    },
    //更新图表配置
    updateChart() {
      if (!this.chartInstance) {
        return
      }
      this.chartInstance.setOption(this.options, true)
    },
    //处理窗口 resize
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize()
      }
    },
    //添加 resize 监听
    addResizeListener() {
      window.addEventListener('resize', this.handleResize)
    },
    //移除 resize 监听
    removeResizeListener() {
      window.removeEventListener('resize', this.handleResize)
    },
    disposeChart() {
      if (this.chartInstance) {
        this.chartInstance.dispose()
        this.chartInstance = null
      }
    }
  },
  watch: {
    options: {
      deep: true,
      handler(newVal, oldVal) {
        this.updateChart()
      }
    }
  }
}
</script>

<style scoped>
.echarts-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
}
</style>
